// ==UserScript==
// @name           re-tweet-plus
// @namespace      rtpl
// @description    Twitterサイト上のツイートに外部サイトのタグや関連エントリーの情報を追加する
// @include        http://twitter.com*
// @include        https://twitter.com*
// @author         mainya
// @author         forked from http://userscripts.org/scripts/show/99236 By vilart 
// @version        1.1
// ==/UserScript==

(function () {
    if (!document.getElementById("top-stuff")) return false;
    var twitterReady = function (callback, afterReady) {
        var uniqueId, correctId;
        var func = function () {
            setTimeout(function () {
                if (twttr) {
                    if (callback()) {
                        var custom = 0;
                    }
                }
            }, 200);
        }
        var funcStr = func.toString();
        if (afterReady) {
            uniqueId = Math.floor(Math.random() * 2147483647);
            correctId = Math.floor(Math.random() * 2147483647);
            var lockerName = "_x_gm_twready_locker_" + uniqueId;
            var openerName = "_x_gm_twready_opener_" + correctId;
            var locker = document.createElement("div");
            locker.setAttribute("id", lockerName);
            locker.setAttribute("style", "display:none;");
            document.body.appendChild(locker);
            locker.addEventListener("DOMNodeInserted", function (e) {
                var isErase = false;
                for (var i = 0; i < locker.childNodes.length; i++) {
                    if (locker.childNodes[i].id == openerName) {
                        isErase = true;
                        break;
                    }
                }
                if (isErase) {
                    document.body.removeChild(locker);
                    afterReady();
                }
            }, false);
            funcStr = funcStr.replace(/var custom = 0;/, 'var e=document.createElement("span");e.setAttribute("id","' + openerName + '");document.getElementById("' + lockerName + '").appendChild(e);');
        }
        var callbackStr = callback.toString();
        var script = document.createElement("script");
        script.innerHTML = "(function(){var callback=" + callbackStr + ";(" + funcStr + ")();})();";
        document.body.appendChild(script);
    }
    var getTag = function (targetElement, tweetId, screenName) {
        var url = "http://retweeters.appspot.com/tweet/" + tweetId + "/tag";
        var args = { url : url };
        chrome.extension.sendRequest(args, function(req) {
            var obj = JSON.parse(req.responseText);
            if (obj && obj.status && obj.status == "OK") {
                var str = "";
                for (key in obj.value) {
                    str += obj.value[key].word;
                    str += "(" + obj.value[key].weight + ") ";
                }
                targetElement.innerHTML += " [ " + str + " ] ";
            }
			else {
                targetElement.innerHTML += " [ " + req.responseText + " ] ";
			}
        });
    };

    twitterReady(function () {
        if (!twttr.templates) return false;
		
        twttr.templates._rtpl_container = '<div class="_rtpl_container unchecked" data-screen-name="{{#user}}{{screen_name}}{{/user}}" data-tweet-id="{{id}}"><a class="_rtpl" target="_blank" href="#"></a></div>';
        twttr.templates.details_pane_tweet = twttr.templates.details_pane_tweet.replace(/{{>tweet_actions}}/, "{{>tweet_actions}}{{>_rtpl_container}}");
        twttr.views.DetailsPaneTweet._template = twttr.templates.details_pane_tweet;
        twttr.templates.permalink_tweet = twttr.templates.permalink_tweet.replace(/{{>tweet_actions}}/, "{{>tweet_actions}}{{>_rtpl_container}}");
        twttr.views.PermalinkTweet._template = twttr.templates.permalink_tweet;
		
        return true;
    }, function () {
        document.body.addEventListener("DOMNodeInserted", function (e) {
            var x = e.relatedNode.getElementsByClassName("_rtpl_container unchecked");
            if (!x.length) {
                return;
            }
            for (var i = 0; i < x.length; i++) {
                var elm = x[i];
                elm.className = "_rtpl_container";
                var tweetId = elm.getAttribute("data-tweet-id");
                var screenName = elm.getAttribute("data-screen-name");
                setTimeout(function () {
                    getTag(elm.getElementsByClassName("_rtpl")[0], tweetId, screenName)
                }, 10);
            }
        }, false);
    });

})();
